package com.gwd.task.services.impl;

import cn.hutool.core.date.DateTime;
import com.gwd.task.componts.Cache;
import com.gwd.task.entity.CodeSubmitRecordEntity;
import com.gwd.task.model.CodeSubmitRecordDTO;
import com.gwd.task.model.transfer.RepositoryInterface;
import com.gwd.task.repository.CodeSubmitRecordRepository;
import com.gwd.task.services.CodeSubmitRecordServer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhiyongming
 * @date 2020/12/22 10:14
 */
@Service
public class CodeSubmitRecordServerImpl implements CodeSubmitRecordServer {

    @Resource
    private Cache cache;
    @Resource
    private CodeSubmitRecordRepository codeSubmitRecordRepository;

    @Override
    public void save(CodeSubmitRecordDTO dto) {
        List<CodeSubmitRecordEntity> list = new ArrayList<>();
        int size = dto.getCodeRepository().length;
        for (int i=0; i<size; i++) {
            String repository = dto.getCodeRepository()[i];
            CodeSubmitRecordEntity entity = new CodeSubmitRecordEntity(dto);
            entity.setRepository(repository);

            list.add(entity);
        }

        codeSubmitRecordRepository.saveAll(list);
        codeSubmitRecordRepository.matchRepository();
    }

    @Override
    public void mergerCode(List<Long> ids, Long userId) {
        String mergerTime = DateTime.now().toStringDefaultTimeZone();
        codeSubmitRecordRepository.mergerCode(userId, mergerTime, ids);
    }

    @Override
    public List<CodeSubmitRecordDTO> findByRepository(Long repId, Long projectId) {
        List<CodeSubmitRecordDTO> list =
                codeSubmitRecordRepository.findByReposAndProject(projectId, repId)
                        .stream().map(CodeSubmitRecordDTO::new).collect(Collectors.toList());

        cache.matchUserName(list, "getSubmitUser", "setSubmitUserName");

        return list;
    }

    @Override
    public List<CodeSubmitRecordDTO> findByRepository(Long repId) {
        List<CodeSubmitRecordDTO> list =
            codeSubmitRecordRepository.findByRepIdAndStatus(repId, 0).stream().map(CodeSubmitRecordDTO::new).collect(Collectors.toList());
        cache.matchUserName(list, "getSubmitUser", "setSubmitUserName");

        return list;
    }

    @Override
    public List<RepositoryInterface> getRepositoryCount() {
        return codeSubmitRecordRepository.countGroupByRep();
    }

    @Override
    public void board(Long crId) {
        codeSubmitRecordRepository.saveAll(codeSubmitRecordRepository.findByRepIdAndStatus(crId, 0).stream().peek(e -> e.setStatus(1)).collect(Collectors.toList()));
    }
}
